package com.tbvtc.agriculturalcreditchainserver2025.redis;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.KeyspaceEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisExpirationConfig {

    @Bean
    public RedisMessageListenerContainer redisMessageListenerContainer(
        RedisConnectionFactory connectionFactory) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer(); // 监听所有事件
        container.setConnectionFactory(connectionFactory); // 使用RedisConnectionFactory
        return container;
    }

    @Bean
    public KeyExpirationListener keyExpirationListener(
        RedisMessageListenerContainer listenerContainer) { // 监听所有事件
        return new KeyExpirationListener(listenerContainer); // 监听所有事件
    }

    public class KeyExpirationListener extends KeyspaceEventMessageListener {
        
        public KeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
            super(listenerContainer);
        }

        @Override
        protected void doHandleMessage(Message message) { // 处理过期事件
            // 使用与存储时相同的序列化方式
            String expiredKey = new StringRedisSerializer().deserialize(message.getBody());
            if (expiredKey != null && expiredKey.startsWith("order:")) {
                handleExpiredOrder(expiredKey);
            }
        }
    }

    private static void handleExpiredOrder(String key) { // 处理过期订单
        String userId = key.split(":")[1];
        // 实现订单过期处理逻辑
        System.out.println("订单过期: " + userId);
    }
}